package com.henry.db.migrate.util;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class StringUtil {


    /**
     * 替换�?���?��字符�?此方法如果目标代码中出现特殊字符，会导致正则无法使用
     * 
     * @param str
     * @param dest
     * @param replacement
     * @return
     */
    @Deprecated
    public static String replaceLast(String str, String dest, String replacement) {
        return str.replaceAll(dest + "(?!.*" + dest + ".*)", replacement);
    }

    /**
     * �ж��ַ��Ƿ�Ϊ��
     * **/
    public static boolean isEmpty(String content) {
        if (content == null || content.trim().equals(""))
            return true;
        return false;
    }

    /*
     * public static String getDocKey(String formatpath) { String str[] = formatpath.split("\\/");
     * int len = str.length - 1; String s = str[len]; int length = s.length() - 4; s =
     * s.substring(0, length); return s; }
     */

    public static String repeat(String sc, int num) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < num; i++)
            sb.append(sc);
        return sb.toString();
    }

    /**
     * 主要是解决在利用split分隔的时候，结尾如果为空，split分隔的数组将会忽略空串的问题
     * 
     * @param regex
     * @param s
     * @return
     * 
     *         by hujun on 2013/10/12
     */
    public static String[] split(String regex, String s) {
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(s);
        int index = 0;
        while (m.find()) {
            index++;
        }
        return s.split(regex, index + 1);
    }

    /**
     * 分析使用","分隔的多个参数，类似函数的参数分析器
     * 
     * @param str 如："abc,2,'cd'"
     * @return
     */
    public static String[] analyseArgs(String str) {
        int len = str.length();
        boolean inStr = false;
        List<String> args = new ArrayList<String>();
        StringBuffer tmpArg = new StringBuffer();
        for (int i = 0; i < len; i++) {
            char c = str.charAt(i);
            if (c == ' ') {
                if (inStr) tmpArg.append(c);
            } else if (c == '\'') {
                inStr = !inStr;
                tmpArg.append(c);
            } else if (c == ',') {
                if (inStr)
                    tmpArg.append(c);
                else {
                    args.add(tmpArg.toString());
                    tmpArg = new StringBuffer();
                }
            } else
                tmpArg.append(c);
        }
        String lastStr = tmpArg.toString();
        if (!lastStr.equals("")) args.add(lastStr);
        return args.toArray(new String[args.size()]);
    }

    /**
     * @param db
     * @pattern 模式
     * **/
    public static String formatDouble(double db, String pattern) {
        DecimalFormat df = new DecimalFormat(pattern);
        return df.format(db);
    }

    public static String formatDouble(double db) {
        String str = (db + "").toLowerCase();
        int index;
        if ((index = str.indexOf('e')) != -1) {
            int len = Integer.parseInt(str.substring(index + 1));
            int dotIndex = str.indexOf('.');
            int lackLen = len - (index - dotIndex - 1);
            if (len > 0) {
                if (lackLen > 0) {
                    return String.format("%.0f", db);
                }
                return str.substring(0, dotIndex) + str.substring(dotIndex + 1, dotIndex + len + 1)
                        + "." + str.substring(dotIndex + len + 1, index);
            } else {
                return String.format("%." + (-lackLen) + "f", db);
            }
        } else
            return str;
    }

    public static String getFillChars(String str, String leftchars, String chars, String direct,
            int totalLen) {
        int left = totalLen - str.length();
        if (left > 0) {
            for (int i = 0; i < left; i++) {
                leftchars = leftchars + chars;
            }
        }
        if (direct.toLowerCase().equals("left")) {
            return leftchars + str;
        } else {
            return str + leftchars;
        }
    }

    public static String convertRightToLeftSlash(String content) {

        return content.replaceAll("\\\\", "/");// 用四个反斜杠来代替一个反斜杠

    }

    public static byte[] getBytes(String srcStr, String encoding)
            throws UnsupportedEncodingException {
        return srcStr.getBytes(encoding);
    }

    public static String bytesToString(byte[] bytes, String encoding)
            throws UnsupportedEncodingException {
        return new String(bytes, encoding);
    }

    public static String bytesToString(byte[] bytes) {
        return new String(bytes);
    }

    public static byte[] getBytes(String srcStr) {
        return srcStr.getBytes();
    }

    /**
     * 按照num指定的长度创建一个由数字组成的随机字符串
     * 
     * @param num
     * @return
     */
    public static String createRandomNumStr(int num) {
        String str = String.format("%." + num + "f", Math.random());
        return str.substring(2);
    }

    /***
     * 字符串填�?
     * 
     * @param s 源数�?可以为String,doule(doule为两位小数类�?,int
     * @param chars 填充字符
     * @param director 包括left right两种情况
     * @param totalLen补充完后的�?长度
     * **/
    public static String fillWithChar(Object obj, String chars, String direct, int totalLen) {
        String leftchars = "";
        if (obj instanceof String) {
            String str = (String) obj;
            return StringUtil.getFillChars(str, leftchars, chars, direct, totalLen);
        } else if (obj instanceof Integer) {
            String str = String.valueOf(obj);
            return getFillChars(str, leftchars, chars, direct, totalLen);
        } else if (obj instanceof Long) {
            String str = String.valueOf(obj);
            return getFillChars(str, leftchars, chars, direct, totalLen);
        } else if (obj instanceof Double) {
            Double d = (Double) obj;
            double dd = d.doubleValue();
            String str = StringUtil.formatDouble(dd);
            str = str.replace(".", "");
            return getFillChars(str, leftchars, chars, direct, totalLen);
        } else if (obj instanceof BigDecimal) {
            BigDecimal b = (BigDecimal) obj;
            DecimalFormat df = new DecimalFormat();
            String st = df.format(b);
            return StringUtil.getFillChars(st, leftchars, chars, direct, totalLen);
        } else {
            return null;
        }
    }

    public static double round(double v, int scale) {
        if (scale < 0)

        {
            throw new IllegalArgumentException("The scale must be a positive integer or zero");

        }

        BigDecimal b = new BigDecimal(Double.toString(v));

        BigDecimal one = new BigDecimal("1");

        return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();

    }

    // 转化字符串为十六进制编码
    public static String toHexString(String s) {
        String str = "";
        for (int i = 0; i < s.length(); i++) {
            int ch = (int) s.charAt(i);
            String s4 = Integer.toHexString(ch);
            str = str + s4;
        }

        return str;
    }

    public static List<String> match(String pattern, String target) {
        Pattern p = Pattern.compile(pattern, Pattern.DOTALL | Pattern.MULTILINE);
        Matcher matcher = p.matcher(target);
        List<String> groupsa = new ArrayList<String>();
        while (matcher.find()) {
            String paramName = matcher.group();
            groupsa.add(paramName);
        }
        return groupsa;
    }

    /**
     * <p>
     * <b>此函数在顺德项目中使�?/b>
     * </p>
     * **/
    public static boolean isNotEmpty(String content) {
        return !isEmpty(content);
    }

    /**
     * 
     * <p>
     * <b>此函数在顺德项目中使�?/b>
     * </p>
     * 
     * @param str 原始字符�?
     * @param subLen 子字符串长长�?
     * @param num 切分个数
     * @return 分割后的子字符串数组
     * @throws UnsupportedEncodingException
     */
    public static String[] divideGBKStr(String str, int subLen, int num)
            throws UnsupportedEncodingException {
        str = str.replace("\r", "").replace("\n", "").trim();
        byte[] strBytes = str.getBytes("GBK");
        String[] strs = new String[num];
        int byteStartIdx = 0;
        int strStartIdx = 0;
        for (int i = 0; i < num; i++) {
            int copyLen =
                    strBytes.length - byteStartIdx >= subLen ? subLen : strBytes.length
                            - byteStartIdx;
            if (copyLen <= 0)
                strs[i] = " ";
            else {
                byte[] subBytes = new byte[copyLen];
                System.arraycopy(strBytes, byteStartIdx, subBytes, 0, copyLen);
                String subStr = new String(subBytes, "GBK");
                int subStrLen = subStr.length();
                int subStrOfStrLen =
                        str.substring(strStartIdx, strStartIdx + subStrLen).getBytes("GBK").length;
                if (subStrOfStrLen > subLen) {
                    subBytes = new byte[copyLen - 1];
                    System.arraycopy(strBytes, byteStartIdx, subBytes, 0, copyLen - 1);
                    byteStartIdx += copyLen - 1;
                    strStartIdx += subStrLen - 1;
                } else {
                    byteStartIdx += copyLen;
                    strStartIdx += subStrLen;
                }
                strs[i] = new String(subBytes, "GBK");
            }
        }
        return strs;
    }

    /**
     * 返回�?��代表当期日期是星期几的数字�?1表示星期天�?2表示星期�??7表示星期�?
     * **/
    public static int getDayOfWeek(String year, String month, String day) {
        Calendar cal =
                new GregorianCalendar(new Integer(year).intValue(),
                        new Integer(month).intValue() - 1, new Integer(day).intValue());
        return cal.get(Calendar.DAY_OF_WEEK);
    }
    
    /**
     * 格式化数字串，保留n位小�?
     * 
     * @param String 数字�?
     * @param int 保留小数位数
     * @return String 错误返回null
     */
    public static String formatDigitalStr(String str, int n) {
        String strResult = "";
        if (str == null) {
            return null;
        }
        if (str.contains(".")) {
            if (str.length() - (str.indexOf('.') + 1) >= n) {
                strResult = str.substring(0, str.indexOf('.') + n + 1);
            } else {
                strResult = String.format("%." + n + "f", Double.parseDouble(str));
            }
        } else {
            strResult = String.format("%." + n + "f", Double.parseDouble(str));
        }
        return strResult;
    }

    /**
     * 字符串是否是数字
     * 
     * @param String 源字符串
     * @return int 0是，-1�?
     */
    public static boolean strIsNumeric(String str) {
        if (str == null || str.trim().length() == 0) {
            return false;
        }
        try {
            @SuppressWarnings("unused")
			long num = Long.parseLong(str.trim());
        } catch (NumberFormatException e) {
            return false;
        }
        return true;
    }

    /**
     * 字符串是否是短整形的
     * 
     * @param String 源字符串
     * @return int 0是，-1�?
     */
    public static int strIsMshort(String str) {
        if (str == null) {
            return -1;
        }
        try {
            @SuppressWarnings("unused")
			int num = Short.parseShort(str);
        } catch (NumberFormatException e) {
            return -1;
        }
        return 0;
    }

    /**
     * 字符串是否是浮点数字( 允许负号 )
     * 
     * @param String 源字符串
     * @return int 0是，-1�?
     */
    public static int strIsFloat(String str) {
        if (str == null) {
            return -1;
        }
        try {
            @SuppressWarnings("unused")
			float num = Float.parseFloat(str);
        } catch (NumberFormatException e) {
            return -1;
        }
        return 0;
    }

    /**
     * 日期时间校验函数 本函数根据输入的掩码对字符串的日期时间进行校�?
     * 
     * @param pszDateTime 输入日期时间
     * @param pszFmt 输入日期时间格式
     * @return 校验是否成功
     */
    public static boolean checkDateTime(String pszDateTime, String pszFmt) {
    	
        if (pszFmt == null || pszFmt.equals("") || pszDateTime == null || pszDateTime.equals("")) {        	
            return false;
        }
        if (pszFmt.length() != pszDateTime.length()) {        	
            return false;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pszFmt);
        try {
            Date date = sdf.parse(pszDateTime);
            long time = date.getTime();            
            if (time > 0) {
                return true;
            } else {
                return false;
            }
        } catch (ParseException e) {        	
            return false;
        }
    }

    /**
     * 字符串是否是Ascii可见字符
     * 
     * @param String 源字符串
     * @return int 0是，-1�?
     * @throws UnsupportedEncodingException 
     */
    public static int strIsGraph(String str) throws UnsupportedEncodingException {
        if (str == null) {
            return -1;
        }
        byte[] byt = str.getBytes("GBK");
        for (int i = 0; i < byt.length; i++) {
            if (byt[i] >= 128 || byt[i] < 32) {
                return -1;
            }
        }
        return 0;
    }

    /**
     * 是否是中�?
     * 
     * @param String 源字符串
     * @return int 0是， -1不是
     * @throws UnsupportedEncodingException 
     */
    public static int strIsChinese(String strSrc) throws UnsupportedEncodingException {
        if (strSrc == null) {
            return -1;
        }
        byte[] str = strSrc.getBytes("GBK");
        if ((str.length % 2) != 0) {
            return -1;
        }
        for (int i = 0; i < str.length; i += 2) {
            if (ischn_2b((str[i]), (str[i + 1])) != 0) return -1;
        }
        return 0;
    }

    /**
     * 判断是否为汉�?
     * 
     * @param int ch1 第一字节�?
     * @param int ch2 第二字节�?
     * @return int 0是，-1�?
     */
    public static int ischn_2b(int ch1, int ch2) {
        int ret;
        ch1=ch1&0xff;
        ch2=ch2&0xff;
        if (ch1 >= 0x81 && ch1 <= 0xFE && (ch2 >= 0x40 && ch2 <= 0xFE && ch2 != 0x7F)) {
            ret = 0;
        } else {
            ret = -1;
        }
        return ret;
    }

    /**
     * 是否全角字符
     * 
     * @param String 源字符串
     * @return int 0�?�?1不是
     * @throws UnsupportedEncodingException 
     */
    public static int strIsSBC(String strSrc) throws UnsupportedEncodingException {
        int i;
        byte[] str = strSrc.getBytes("GBK");
        if ((str.length % 2) != 0) return -1;

        for (i = 0; i < str.length; i += 2) {
            if ((str[i] & 0XFF) > 0x20 && (str[i] & 0XFF) < 0x7f) return -1;
        }
        return 0;
    }

    /**
     * 判断是否为汉字第�?���?
     * 
     * @param int ch 字节�?
     * @return int 0是，-1�?
     */
    public static int ischn_fb(int ch) {    	
        int ret;
        ch=ch&0xff;
        if (ch > 0x80 && ch < 0xFF) {  //ch >128 and ch<255
            ret = 0;
        } else {
            ret = -1;
        }        
        return ret;
    }

    /**
     * 判断字符串中pos位置的字符是否为汉字
     * 
     * @param String 源字符串
     * @param int pos pos位置字节�?
     * @return int 0 不是�?1 是第�?��节； 2 是第二字�?
     */
    public static int ischn_instr(String strSrc, int pos) {
        int i = 0;
        int ret;
        if (strSrc == null || pos < 0) {
            return 0;
        }
        byte[] str = strSrc.getBytes();
        if (pos > str.length) {
            return 0;
        }
        if ((str[pos] & 0XFF) < 0x40) {
            return 0;
        }
        while (i < pos) {
            ret = ischn_2b((str[i]), (str[i + 1]));
            if (ret == 0) {
                i += 2;
                if (i > pos) return 2;
            } else {
                i++;
            }
        }
        ret = ischn_fb(str[pos]);
        if (ret == 0) {
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 判断字符串中是否有生僻字
     * 
     * @param String 源字符串
     * @return int 0是，-1不是
     */
    public static int strIsPartStrange(String str) {
        if (str == null) {
            return -1;
        }
        if (str.length() % 2 != 0) {
            return -1;
        }
        char[] charArray = str.toCharArray();
        for (int i = 0; i < charArray.length; i = i + 2) {
            if (isPartStrange_2b((int) charArray[i], (int) charArray[i + 1])) {
                return 0;
            }
        }
        return -1;
    }

    /**
     * 判断汉字是否是生僻字
     * 
     * @param int 第一字节
     * @param int 第二字节
     * @return boolean true是，false不是
     */
    public static boolean isPartStrange_2b(int begin, int end) {
        boolean flag = false;
        begin=begin&0xff;
        end=end&0xff;
        if (begin >= 0x81 && begin <= 0xA0 || (end >= 0x40 && end <= 0xA0 && end != 0x7F)) {
            flag = true;
        }
        return flag;
    }
}
